package com.joint.web.action.app;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.DataUtil;
import com.google.common.collect.Maps;
import com.joint.base.entity.Company;
import com.joint.base.entity.FileManage;
import com.joint.base.entity.Users;
import com.joint.base.entity.system.Locations;
import com.joint.base.service.UsersService;
import com.joint.core.entity.Linkman;
import com.joint.core.entity.ProInfo;
import com.joint.core.entity.ProLeave;
import com.joint.core.entity.ProSignIn;
import com.joint.core.service.ProInfoService;
import com.joint.core.service.ProLeaveService;
import com.joint.core.service.ProSignInService;
import com.joint.web.action.BaseAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.math.BigDecimal;
import java.util.*;


/**
 * 后台Action类 - 用户管理
 * ============================================================================
 * 版权所有 2013 。
 * ----------------------------------------------------------------------------
 * 
 * @author qiushihua
 * 
 * @version 0.1 2013-5-28
 */
@ParentPackage("app")
public class UsersAction extends BaseAction {

	private static final long serialVersionUID = 8202347989251669855L;

    private static final char[] letters = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

	private String uid;//用户ID
	private String loginUserName;
	private String loginPassWord;
	private String keep_login;
	
	private String loginHost;
	private String loginConnection;
	private String loginCookie;
	private String loginUserAgent;
	
	private String MapKey;//key
	private String UserName;//手机号
	private int Type;//类型（找回密码1|注册0）
	private String Step;//步奏
	private String AuthCode;//验证码
	private String PassWord;//密码
	private String OldPassWord;//旧密码
	
	private File portrait;
	private String portraitFileName;
	private String portraitContentType;
	
	private FileManage fileManage;
	private Set<FileManage> fileManageSet;
	
	private String name;//姓名
	private String mobile;//手机

    //账号转移
    private String companyCode_1;//企业Id
    private String companyCode_2;
    private String remark;//验证信息
	
	private long _startTime;
	private long _endTime;
    private String proinfoId;//某一项目信息的id
	private Company company;//公司
	
	private List<Users> usersList;
	private Iterator<Users> usersIterator;

	private Users otherUsers;//用户
	private Linkman linkman;//联系人

	private Locations locations;//位置
    private ProInfo proInfo;

    @Resource
    private ProSignInService proSignInService;
    @Resource
    private ProInfoService proInfoService;
    @Resource
    private ProLeaveService proLeaveService;
	@Resource
	private UsersService usersService;

    /**
     * 用户列表
     *
     * @return String
     * @throws Exception
     */
    public String getList() throws Exception {
        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        pager = new Pager();
        pager.setPageNumber(pageIndex);// 页码
        pager.setPageSize(pageSize);// 页Size
        if(StringUtils.isNotEmpty(pageProperty)&&StringUtils.isNotEmpty(pageKeyword)){
            pager.setProperty(pageProperty);
            pager.setKeyword(pageKeyword);
        }
        pager.setOrderType(BaseEnum.OrderType.asc);
        pager.setOrderBy("pinYinHead");

        pager = usersService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[] { BaseEnum.StateEnum.Enable });
        usersList = (List<Users>) pager.getList();

        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        int count = 0;

        if(usersList.size()>0){
            for(Users users:usersList){
                Map<String, Object> tempMap = usersService.getListItemMap(users);
                dataRows.add(JSONObject.fromObject(tempMap));
            }
        }

        data.put("pageNum", pageIndex);//页数
        data.put("pageSize", count);
        data.put("pageCount", pager.getPageCount());
        data.put("totalCount", pager.getTotalCount());
        data.put("dataRows", JSONArray.fromObject(dataRows));
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    public String getPYGroupList(){
        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        pager = new Pager(0);
        if(StringUtils.isNotEmpty(pageProperty)&&StringUtils.isNotEmpty(pageKeyword)){
            pager.setProperty(pageProperty);
            pager.setKeyword(pageKeyword);
        }
        pager.setOrderType(BaseEnum.OrderType.asc);
        pager.setOrderBy("pinYinHead");

        pager = usersService.findByPagerAndCompany(pager, null, company, new BaseEnum.StateEnum[] { BaseEnum.StateEnum.Enable });
        usersList = (List<Users>) pager.getList();

        if (usersList == null) {
            usersList = new ArrayList<Users>();
        }

        Map<String, Object> data = new HashMap<String, Object>();
        List<JSONObject> dataRows = new ArrayList<JSONObject>();
        Map<String, Object> keyData;
        List<JSONObject> keyDataRows = new ArrayList<JSONObject>();
        Map<String, Object> tempMap;

        char nowTag ='\0';
        if(usersList.size()>0){
            for(int i=0;i<usersList.size();i++){
                Users item = usersList.get(i);
                char tempTag = item.getPinYinHead().charAt(0);
                if(Arrays.binarySearch(letters, tempTag) < 0){
                    tempTag = '#';
                }
                if (nowTag != tempTag) {
                    if (keyDataRows.size()>0){
                        keyData = new HashMap<String, Object>();
                        keyData.put("key", nowTag);
                        keyData.put("value", JSONArray.fromObject(keyDataRows));
                        dataRows.add(JSONObject.fromObject(keyData));
                    }
                    keyDataRows.clear();
                    nowTag = tempTag;
                }
                tempMap = usersService.getListItemMap(item);
                keyDataRows.add(JSONObject.fromObject(tempMap));
                //最后一个
                if (i == usersList.size()-1){
                    if (keyDataRows.size()>0){
                        keyData = new HashMap<String, Object>();
                        keyData.put("key", nowTag);
                        keyData.put("value", JSONArray.fromObject(keyDataRows));
                        dataRows.add(JSONObject.fromObject(keyData));
                    }
                }
            }
        }

        data.put("pageNum", 0);//页数
        data.put("pageSize", usersList.size());
        data.put("pageCount", pager.getPageCount());
        data.put("totalCount", pager.getTotalCount());
        data.put("dataRows", JSONArray.fromObject(dataRows));
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    /**
     * 日历日期(计算那几天有日历项)
     * @return String
     * @throws Exception
     */
    public String getCalendarDateList() throws Exception {
        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        if(_startTime>0&&_endTime>0){
            Date dateS = new Date(_startTime);
            Date dateE = new Date(_endTime);
            Map<String, Object> data = new HashMap<String, Object>();
            Set<String> dateSet = new HashSet<String>();
            //项目签到
            Map rmap = Maps.newHashMap();
            if(StringUtils.isNotEmpty(proinfoId)){
                proInfo = proInfoService.get(proinfoId);
                rmap.put("proInfo",proInfo);
            }
            rmap.put("state",BaseEnum.StateEnum.Enable);
            List<ProSignIn> proSignInList = (List<ProSignIn>)proSignInService.findByPagerAndCompany(
                    new Pager(0),"createDate",dateS,dateE,null,company,rmap).getList();
            if(proSignInList.size()>0){
                for(ProSignIn proSignIn : proSignInList){
                    dateSet.addAll(DataUtil.getBewteenDates(proSignIn.getCreateDate(), null, dateS, dateE));
                }
            }
//            LogUtil.info("{ dateList1 }" + JSONArray.fromObject(dateSet));
            //项目请假
            List<ProLeave> proLeaveList = (List<ProLeave>)proLeaveService.findByPagerAndCompany(
                    new Pager(0),"leaveDate",dateS,dateE,null,company,rmap).getList();
            if(proLeaveList.size()>0){
                for(ProLeave proLeave : proLeaveList){
                    dateSet.addAll(DataUtil.getBewteenDates(proLeave.getLeaveDate(), null, dateS, dateE));
                }
            }
//            LogUtil.info("{ dateList2 }" + JSONArray.fromObject(dateSet));
            data.put("dateList", JSONArray.fromObject(dateSet));
            return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
        }
        return ajaxHtmlAppResult(0, "查询失败！",null);
    }

    /**
     * 日历事件(某一天下的事件)
     *
     * @return String
     * @throws Exception
     */
    public String getCalendarList() throws Exception {
        users = getRequestUsers();
        company = users.getCompany();
        if(company == null)
            return ajaxHtmlAppResult(0, "未找到用户所属企业！",null);

        if(_startTime>0&&_endTime>0){
            pager = new Pager(0);
            Date dateS = new Date(_startTime);
            Date dateE = new Date(_endTime);
            List<JSONObject> dataRows = new ArrayList<JSONObject>();
            Map<String, Object> data = new HashMap<String, Object>();
            //项目签到
            Map rmap = Maps.newHashMap();
            if(StringUtils.isNotEmpty(proinfoId)){
                proInfo = proInfoService.get(proinfoId);
                rmap.put("proInfo",proInfo);
            }
            rmap.put("state",BaseEnum.StateEnum.Enable);
            List<ProSignIn> proSignInList = (List<ProSignIn>)proSignInService.findByPagerAndCompany(
                    pager,"createDate",dateS,dateE,null,company,rmap).getList();

            if(proSignInList.size()>0){
                for(ProSignIn proSignIn : proSignInList){
                    Map<String, Object> jsonMap = new HashMap<String, Object>();
                    jsonMap.put("name", "[项目签到]["+proSignIn.getCreater().getName()+"] "+((proSignIn.getStatus()==1)?"正常":"迟到"));
                    String remark = DataUtil.DateMinToString(proSignIn.getCreateDate());
                    jsonMap.put("time", remark);
                    jsonMap.put("remark", remark + " [" + proSignIn.getProInfo().getName() + "]");
                    jsonMap.put("type", "Signin");

                    jsonMap.put("id", proSignIn.getId());
                    dataRows.add(JSONObject.fromObject(jsonMap));
                }
            }
//            LogUtil.info("{ dateList1 }" + JSONArray.fromObject(dataRows));
            //项目请假
            List<ProLeave> proLeaveList = (List<ProLeave>)proLeaveService.findByPagerAndCompany(
                    pager,"leaveDate",dateS,dateE,null,company,rmap).getList();
            if(proLeaveList.size()>0){
                for(ProLeave proLeave : proLeaveList){
                    Map<String, Object> jsonMap = new HashMap<String, Object>();
                    jsonMap.put("name", "[项目请假]["+proLeave.getCreater().getName()+"] "+ proLeave.getReason());
                    String remark = DataUtil.DateMinToString(proLeave.getLeaveDate());
                    jsonMap.put("time", remark);
                    jsonMap.put("remark", remark + " [" + proLeave.getProInfo().getName() + "]");
                    jsonMap.put("type", "Leave");

                    jsonMap.put("id", proLeave.getId());
                    dataRows.add(JSONObject.fromObject(jsonMap));
                }
            }
//            LogUtil.info("{ dateList2 }" + JSONArray.fromObject(dataRows));

            if(dataRows.size()>0){
                data.put("pageSize", dataRows.size());
                data.put("pageCount", pager.getPageCount());
                data.put("dataRows", JSONArray.fromObject(dataRows));
            }else{
                data.put("pageSize", 0);
                data.put("pageCount", 0);
                data.put("dataRows", "");
            }

            return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
        }
        return ajaxHtmlAppResult(0, "查询失败！",null);
    }


	
	/**
	 * 关注用户选择列表
	 * @return
	 * @throws Exception
	 */
	public String getUserFriendPickList() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession httpSession = request.getSession();
		
		System.out.println("SessionId:"+httpSession.getId());
		System.out.println("Host:"+request.getHeader("Host"));
		System.out.println("Connection:"+request.getHeader("Connection"));
		System.out.println("Cookie:"+request.getHeader("Cookie"));
		System.out.println("User:"+request.getHeader("User-Agent"));
		
		System.out.println("uid:"+request.getParameter("uid"));
		
		if(StringUtils.isNotEmpty(uid)){
			users = usersService.get(uid);
			if(users == null){
				return ajaxHtmlAppResult(0, "未找到当前用户！",null);
			}
			if(locations==null||locations.getLongitude()==null||locations.getLongitude().compareTo(BigDecimal.ZERO)<=0||locations.getLatitude()==null||locations.getLatitude().compareTo(BigDecimal.ZERO)<=0){
				return ajaxHtmlAppResult(0, "查询失败！",null);
			}
			//Json生成
			List<JSONObject> dataRows = new ArrayList<JSONObject>();
			Map<String, Object> data = new HashMap<String, Object>();

		}else{
			return ajaxHtmlAppResult(0, "您还未登陆！",null);
		}
		return AuthCode;
	}

	public String getLoginUserName() {
		return loginUserName;
	}

	public void setLoginUserName(String loginUserName) {
		this.loginUserName = loginUserName;
	}

	public String getLoginPassWord() {
		return loginPassWord;
	}

	public void setLoginPassWord(String loginPassWord) {
		this.loginPassWord = loginPassWord;
	}

	public String getKeep_login() {
		return keep_login;
	}

	public void setKeep_login(String keep_login) {
		this.keep_login = keep_login;
	}

	public String getMapKey() {
		return MapKey;
	}

	public void setMapKey(String mapKey) {
		MapKey = mapKey;
	}

	public String getUserName() {
		return UserName;
	}

	public void setUserName(String userName) {
		UserName = userName;
	}

	public int getType() {
		return Type;
	}

	public void setType(int type) {
		Type = type;
	}

	public String getStep() {
		return Step;
	}

	public void setStep(String step) {
		Step = step;
	}

	public String getAuthCode() {
		return AuthCode;
	}

	public void setAuthCode(String authCode) {
		AuthCode = authCode;
	}

	public String getPassWord() {
		return PassWord;
	}

	public void setPassWord(String passWord) {
		PassWord = passWord;
	}

	public String getUid() {
		return uid;
	}

	public void setUid(String uid) {
		this.uid = uid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}



	public String getMobile() {
		return mobile;
	}

	public void setMobile(String mobile) {
		this.mobile = mobile;
	}



	public String getOldPassWord() {
		return OldPassWord;
	}

	public void setOldPassWord(String oldPassWord) {
		OldPassWord = oldPassWord;
	}

	public Linkman getLinkman() {
		return linkman;
	}

	public void setLinkman(Linkman linkman) {
		this.linkman = linkman;
	}

	public Locations getLocations() {
		return locations;
	}

	public void setLocations(Locations locations) {
		this.locations = locations;
	}

	public File getPortrait() {
		return portrait;
	}

	public void setPortrait(File portrait) {
		this.portrait = portrait;
	}

	public String getPortraitFileName() {
		return portraitFileName;
	}

	public void setPortraitFileName(String portraitFileName) {
		this.portraitFileName = portraitFileName;
	}

	public String getPortraitContentType() {
		return portraitContentType;
	}

	public void setPortraitContentType(String portraitContentType) {
		this.portraitContentType = portraitContentType;
	}

	public long get_startTime() {
		return _startTime;
	}

	public void set_startTime(long _startTime) {
		this._startTime = _startTime;
	}

	public long get_endTime() {
		return _endTime;
	}

	public void set_endTime(long _endTime) {
		this._endTime = _endTime;
	}

    public String getCompanyCode_1() {
        return companyCode_1;
    }

    public void setCompanyCode_1(String companyCode_1) {
        this.companyCode_1 = companyCode_1;
    }

    public String getCompanyCode_2() {
        return companyCode_2;
    }

    public void setCompanyCode_2(String companyCode_2) {
        this.companyCode_2 = companyCode_2;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getProinfoId() {
        return proinfoId;
    }

    public void setProinfoId(String proinfoId) {
        this.proinfoId = proinfoId;
    }
}
